package com.yumeng.framework.auth.shiro.matcher;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.yumeng.common.auth.BaseAuthInfo;
import com.yumeng.framework.auth.jwt.JwtUtils;
import com.yumeng.framework.auth.shiro.token.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;

/**
 *
 * @author wxd
 * @date 2022/4/15 10:58
 */
@Slf4j
public class JwtCredentialsMatcher implements CredentialsMatcher {
    @Override
    public boolean doCredentialsMatch(AuthenticationToken authToken, AuthenticationInfo info) {
        String jwt = authToken.getPrincipal().toString();
        String salt = info.getCredentials().toString();
        BaseAuthInfo authInfo = (BaseAuthInfo) info.getPrincipals().getPrimaryPrincipal();
        log.debug("JwtCredentialsMatcher:token-{}", jwt);
        log.debug("JwtCredentialsMatcher:salt-{}", salt);
        boolean b = false;
        try{
            b = JwtUtils.verifyToken(jwt, salt, authInfo.getAuthKey(), authInfo.getIdentityId(), null);
        }catch (TokenExpiredException e){
            //当jwt超时，若RefreshToken有效，传入窗口缓冲时间，过滤超时条件再次验证
            if (authToken instanceof JwtToken){
                JwtToken jwtToken = (JwtToken)authToken;
                if (StringUtils.isNotBlank(jwtToken.getRefreshToken())){
                    //TODO 是否需要在此处验证
                    JwtUtils.checkRefreshCode(jwtToken.getToken(), jwtToken.getRefreshToken());
                    long acceptExpiresAt = JwtUtils.getLeewayForExpiresAt(jwtToken.getToken());//窗口缓冲时间
                    b = JwtUtils.verifyToken(jwt, salt, authInfo.getAuthKey(), authInfo.getIdentityId(), acceptExpiresAt);
                }
            }
        }
        return b;
    }
}
